package com.datamation.swadeshi.view;

import java.util.ArrayList;

import com.datamation.swadeshi.R;
import com.datamation.swadeshi.adapter.LoadingDetAdapter;
import com.datamation.swadeshi.adapter.SetTitleAdapter;
import com.datamation.swadeshi.control.GPSTracker;
import com.datamation.swadeshi.control.LoadingPrintPreviewAlertBox;
import com.datamation.swadeshi.control.ReferenceNum;
import com.datamation.swadeshi.control.SalesPrintPreviewAlertBox;
import com.datamation.swadeshi.control.Toast;
import com.datamation.swadeshi.control.data.FTranDetDS;
import com.datamation.swadeshi.control.data.FTranHedDS;
import com.datamation.swadeshi.control.data.LocationsDS;
import com.datamation.swadeshi.control.data.OrdDetDS;
import com.datamation.swadeshi.control.data.OrdHedDS;
import com.datamation.swadeshi.control.data.SalRepDS;
import com.datamation.swadeshi.model.FTranDet;
import com.datamation.swadeshi.model.FTranHed;
import com.datamation.swadeshi.model.ItemLoc;
import com.datamation.swadeshi.model.OrdHed;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;

public class FragmentInventoryControlLoadingSummery extends Fragment{
	View view;
	ListView lv_invent_load;
	ArrayList<FTranDet> loadlist;
	ReferenceNum referenceNum;
	FragmentItemlocstockUpdate Itemstockupdate;
	ItemLoc Locdetails;
	EditText locfrom,locto;
	Toast  toast;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.inventory_control_loadingsummery, container, false);

		setHasOptionsMenu(true);
        //set title
		SetTitleAdapter objTitle =new SetTitleAdapter();
		objTitle.createCutomActionBarTitle("Loading Summery", getActivity());
		referenceNum=new  ReferenceNum(getActivity());
		Locdetails = new  ItemLoc();
		Itemstockupdate =new FragmentItemlocstockUpdate(getActivity());
		locfrom =(EditText)view.findViewById(R.id.etlocfrom_item_view);
		locto = (EditText)view.findViewById(R.id.etlocto_item_view);
		toast = new Toast();
		fatchData();
		loadtemp();
		FTranHedDS dsg=new FTranHedDS(getActivity());
		final ArrayList<String> list= dsg.gettranhed(referenceNum.getCurrentRefNo(getResources().getString(R.string.LodNumVal)));
		if(list.toString().equals("[]"))
		{
			
			toast.createToastMessage("Please select Item", getActivity());
			getActivity().getActionBar().setSelectedNavigationItem(0);
			
		}
		else 
		{
		}
		return view;
	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		
		for(int i = 0; i < menu.size(); ++i)
		{
			menu.removeItem(menu.getItem(i).getItemId());
		}
		
		inflater.inflate(R.menu.frag_per_sales_summary, menu);

		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.action_pre_sale_undo)
		{
			//MenuItem item1= menu.findItem(R.id.menu_settings);
			undoEditingData(getActivity());
		    
		}
		if(item.getItemId() == R.id.action_pre_sales_save)
		{
			setBluetooth(true);
			//item.setVisible(false);
			saveSummaryDialog(getActivity());
			//item.
			
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	public void fatchData()
	{
		try {
			MainActivity activity =(MainActivity) getActivity();
			lv_invent_load = (ListView) view.findViewById(R.id.lv_loading_sum);
			lv_invent_load.clearTextFilter();
			FTranDetDS detDS = new FTranDetDS(getActivity());
			loadlist = detDS.getAllloadDetails(activity.selectFtranHed.getFTRANHED_REFNO());
			lv_invent_load.setAdapter(new LoadingDetAdapter(getActivity(), loadlist));
		}catch (NullPointerException e){
			Log.v("Loading Error", e.toString());
		}
	}
	
	
	public void loadtemp() 
	{
		FTranHedDS hedDS =new FTranHedDS(getActivity());
		ArrayList<FTranHed> getFtranhed = hedDS.getAllActiveFtranHed(referenceNum.getCurrentRefNo(getResources().getString(R.string.LodNumVal)));
	if(!getFtranhed.isEmpty())
	{
		LocationsDS LOCF =new LocationsDS(getActivity());
		for (FTranHed ftrn : getFtranhed)
			{
				locfrom.setText(LOCF.getItemNameByCode(ftrn.getFTRANHED_LOCFROM()));
				locto.setText(LOCF.getItemNameByCode(ftrn.getFTRANHED_LOCTO()));
			}
		}
	}
	
	private void saveSummaryDialog(final Context context){

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		//alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage("Are you sure you want to save this entry?");
		alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		alertDialogBuilder.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() 
				{
							public void onClick(DialogInterface dialog, int id) 
							{

									FTranHed hed =new FTranHed();
									FTranHedDS ftranhed =new FTranHedDS(getActivity());
									FTranDetDS detDS=new FTranDetDS(getActivity());
									ArrayList<FTranHed> lodHedList=new ArrayList<FTranHed>();
									GPSTracker gpsTracker=new GPSTracker(getActivity());
									
									ReferenceNum referenceNum =new  ReferenceNum(getActivity());
									
									new SalRepDS(getActivity());
									ArrayList<FTranHed> getftranHed = ftranhed.getAllActiveFtranHed(referenceNum.getCurrentRefNo(getResources().getString(R.string.LodNumVal)));
									ArrayList<FTranDet> getftrandet = detDS.getAllloadDetails(referenceNum.getCurrentRefNo(getResources().getString(R.string.LodNumVal)));
															
									if(!getftrandet.isEmpty())
									{
											
											for (FTranDet ftrn : getftrandet)
											{
												//ftranhed.getLocCodebyRefNo(ftrn.getFTRANDET_REFNO());
												
												
												//String sdds = getftranHed.get(0).getFTRANHED_LOCTO();
												FragmentItemlocstockUpdate state = new FragmentItemlocstockUpdate(getActivity());
												state.IS_Update(ftrn.getFTRANDET_ITEMCODE(),ftrn.getFTRANDET_LOCCODE(),getftranHed.get(0).getFTRANHED_LOCTO(),ftranhed.getLocCodebyRefNo(ftrn.getFTRANDET_REFNO()).toString(),ftrn.getFTRANDET_QTY(), "D");

											}
											//ArrayList<FTranHed> ordHedList=new ArrayList<FTranHed>();
											
											MainActivity activity =(MainActivity) getActivity();
											lodHedList.add(activity.selectFtranHed);
											hed.setFTRANHED_REFNO(referenceNum.getCurrentRefNo(getResources().getString(R.string.LodNumVal)));
										
											String HedTotAmt="";
											Double totalAmountVal=Double.parseDouble(detDS.getTotalReturns(referenceNum.getCurrentRefNo(getResources().getString(R.string.LodNumVal))));
											HedTotAmt = (String.format("%,.2f",totalAmountVal));
											hed.setFTRANHED_TOTALAMT(HedTotAmt);
											hed.setFTRANHED_LATITUDE(gpsTracker.getLatitude()+"");
											hed.setFTRANHED_LONGITUDE(gpsTracker.getLongitude()+"");
											hed.setFTRANHED_IS_SYNCED("0");
											hed.setFTRANHED_ACTIVE_STATE("0");
											lodHedList.add(hed);

											if(ftranhed.Finalupdate(lodHedList)>0)
											{

												LoadingPrintPreviewAlertBox alertBox=new LoadingPrintPreviewAlertBox(getActivity());
												alertBox.PrintDetailsDialogbox(getActivity(), "",referenceNum.getCurrentRefNo(getResources().getString(R.string.LodNumVal)));
												
												//next refno
												referenceNum.nNumValueInsertOrUpdate(getResources().getString(R.string.NumVal));

												
												toast.createToastMessage("Save Sucessfull", getActivity());
												getActivity().getActionBar().setSelectedNavigationItem(0);
												activity.getActionBar().removeAllTabs();
												activity.getActionBar().setNavigationMode(0);
												Toast toast=new Toast();
												referenceNum.nNumValueInsertOrUpdate(getResources().getString(R.string.LodNumVal));
												toast.createToastMessage("Loading saved to database.", getActivity());
												getActivity().getFragmentManager().popBackStack();
												dialog.dismiss();
												
											}
											else 
											{
												
												if(!getftrandet.isEmpty())
												{
														
														for (FTranDet ftrn : getftrandet)
														{
															FragmentItemlocstockUpdate state = new FragmentItemlocstockUpdate(getActivity());
															state.IS_Update(ftrn.getFTRANDET_ID(),ftrn.getFTRANDET_LOCCODE(),getftranHed.get(0).getFTRANHED_LOCTO(),ftranhed.getLocCodebyRefNo(ftrn.getFTRANDET_REFNO()).toString(),ftrn.getFTRANDET_QTY(), "A");

														}
														
													}
												toast.createToastMessage("Save Not Sucessfull", getActivity());
												
											}
										}
									else
										{
										toast.createToastMessage("No Item For Save", getActivity());
										}

								}
						})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
						    	dialog.cancel();
							}
						});
		
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	}
	private void undoEditingData(final Context context){

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		//alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage("Are you sure you want to Undo this entry?");
		final FTranHedDS FtrnHED =new FTranHedDS(getActivity());
		final FTranDetDS FtrnDET=new FTranDetDS(getActivity());
		alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								
								ReferenceNum referenceNum =new  ReferenceNum(getActivity());
								MainActivity activity =(MainActivity) getActivity(); 
								
								//delete data
								try {
									FtrnHED.DeltranHed(referenceNum.getCurrentRefNo(getResources().getString(R.string.LodNumVal))); 
								}catch(Exception e){
									Log.w("Reset FtranHed Data Erorrrr ", e.toString());
								}
								try {
									FtrnDET.DeltranDet(referenceNum.getCurrentRefNo(getResources().getString(R.string.LodNumVal))); 
								}catch(Exception e){
									Log.w("Reset FtranDet Data Erorrrr ", e.toString());
								}
								
								activity.cusPosition=0;
								activity.selectedDebtor=null;
								activity.selectedOrdHed=null;
								
								//Toast toast=new Toast();
								toast.createToastMessage("Undo Success", getActivity());
								getActivity().getActionBar().setSelectedNavigationItem(0);
							}
					})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								
								dialog.cancel();
								
								
							}
						});
		
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	}
	
	public static boolean setBluetooth(boolean enable) {
	    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	    boolean isEnabled = bluetoothAdapter.isEnabled();
	    if (enable && !isEnabled) {
	        return bluetoothAdapter.enable(); 
	    }
	    else if(!enable && isEnabled) {
	        return bluetoothAdapter.disable();
	    }
	    // No need to change bluetooth state
	    return true;
	}
	
}
